﻿#region License
/*Copyright (c) 2010 Andrew Collard (andrewcollard@hotmail.com)

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.*/
#endregion

using System;
using System.Diagnostics;
using System.IO;
using System.Collections.Generic;

namespace TorchView.Game
{
  /// <summary>
  /// A saved torchlight game
  /// </summary>
  public class SaveGame
  {
    const string GAME_BACKUP_EXT = "bak";

    public string Filename { get; private set; }
    //public bool SuccessFullyParsedFile { get; private set; }
    //public string ParsingErrorMessage { get; private set; }

    public uint FileVersion { get; set; }
    public string ClassName { get; set; }
    public Difficulty Difficulty { get; set; }
    public bool Hardcore { get; set; }
    public uint Ancestors { get; set; }
    public bool Retired { get; set; }
    public Character MainCharacter { get; set; }
    public FunctionKeyMapping[] FunctionKeys { get; set; }
    public long[] QuickSlots { get; set; }
    public Journal JournalEntries { get; set; }

    #region Dungeons
    public string CurrentDungeonName { get; set; }
    public string PreviousDungeonName { get; set; }
    public uint Unknown2 { get; set; }
    public TownPortal ReturnPortal { get; set; }
    public Character[] Minions { get; set; }
    public TipRead TipsRead { get; set; }
    public ActiveDungeon[] Dungeons { get; set; }
    public PastDungeon[] DungeonHistory { get; set; }
    #endregion

    #region Quests
    public string[] CompletedQuests { get; set; }
    public IncompleteQuest[] IncompleteQuests { get; set; }
    #endregion

    /// <summary>
    /// Get the list of save game files
    /// </summary>
    /// <returns>The current saved games</returns>
    public static string[] GetFileList()
    {
      return Directory.GetFiles(Torchlight.SaveDirectory, "*." + Torchlight.SavedGameExtension);
    }

    /// <summary>
    /// Load a Torchlight game file
    /// </summary>
    /// <param name="filename">SVT File to load</param>
    /// <returns>The game from the specified file</returns>
    public static SaveGame Load(string filename)
    {
      SaveGame game = new SaveGame { Filename = filename };
      BinaryReader reader = null;
      try
      {
        reader = new BinaryReader(new FileStream(filename, FileMode.Open, FileAccess.Read));

        ReadFirstSection(game, reader);
        ReadMainCharacter(game, reader);
        ReadKeyBindings(game, reader);
        ReadJournal(game, reader);
        ReadDungeons(game, reader);
        ReadDungeonHistory(game, reader);
        ReadCompletedQuests(game, reader);
        ReadIncompletedQuests(game, reader);
        var fileLength = reader.ReadUInt32();
        Debug.Assert(fileLength == reader.BaseStream.Length);
        //game.SuccessFullyParsedFile = true;
      }
      //catch (InvalidDataException e) { game.ParsingErrorMessage = e.Message; }
      finally
      {
        if (reader != null)
          reader.Close();
      }
      return game;
    }

    /// <summary>
    /// This block contains the class, difficulty, hardcore, etc...
    /// </summary>
    private static void ReadFirstSection(SaveGame game, BinaryReader reader)
    {
      game.FileVersion = reader.ReadUInt32();
      game.ClassName = SVTHelper.ReadString(reader);
      game.Difficulty = (Difficulty)reader.ReadUInt32();
      game.Hardcore = reader.ReadBoolean();
      game.Ancestors = reader.ReadUInt32();
      game.Retired = reader.ReadBoolean();
    }

    private static void ReadMainCharacter(SaveGame game, BinaryReader reader)
    {
      game.MainCharacter = Character.Read(reader);
    }

    private static void ReadJournal(SaveGame game, BinaryReader reader)
    {
      game.JournalEntries = Journal.Read(reader);
    }

    private static void ReadKeyBindings(SaveGame game, BinaryReader reader)
    {
      ushort skillSlots = reader.ReadUInt16();
      long[] slots = new long[skillSlots];
      for (int i = 0; i < skillSlots; i++)
        slots[i] = reader.ReadInt64();

      ushort fKeysCount = reader.ReadUInt16();
      FunctionKeyMapping[] fKeys = new FunctionKeyMapping[fKeysCount];
      for (int i = 0; i < fKeysCount; i++)
        fKeys[i] = new FunctionKeyMapping { FunctionKey = (FunctionKey)i, uuid = reader.ReadInt64(), unknown = reader.ReadInt64() };

      game.FunctionKeys = fKeys;

      ushort itemSlots = reader.ReadUInt16();
      for (int i = 0; i < itemSlots; i++)
        slots[i] = reader.ReadInt64();

      game.QuickSlots = slots;
    }

    private static void ReadDungeons(SaveGame game, BinaryReader reader)
    {
      game.CurrentDungeonName = SVTHelper.ReadString(reader);
      game.PreviousDungeonName = SVTHelper.ReadString(reader);
      game.Unknown2 = reader.ReadUInt32();
      game.ReturnPortal = TownPortal.Read(reader);
      ReadMinions(game, reader);
      game.TipsRead = TipRead.Read(reader);

      uint dungeonCount = reader.ReadUInt32();
      ActiveDungeon[] dungeons = new ActiveDungeon[dungeonCount];
      for (int i = 0; i < dungeonCount; i++)
        dungeons[i] = ActiveDungeon.Read(reader);
      game.Dungeons = dungeons;
    }

    private static void ReadMinions(SaveGame game, BinaryReader reader)
    {
      uint minionCount = reader.ReadUInt32();
      Character[] minions = new Character[minionCount];
      for (int i = 0; i < minionCount; i++)
        minions[i] = Character.Read(reader);
      game.Minions = minions;
    }

    private static void ReadDungeonHistory(SaveGame game, BinaryReader reader)
    {
      uint dungeoncount = reader.ReadUInt32();
      PastDungeon[] dungeonhistory = new PastDungeon[dungeoncount];
      for (int i = 0; i < dungeoncount; i++)
        dungeonhistory[i] = PastDungeon.Read(reader);
      game.DungeonHistory = dungeonhistory;
    }

    private static void ReadCompletedQuests(SaveGame game, BinaryReader reader)
    {
      uint completedQuestCount = reader.ReadUInt32();
      string[] quests = new string[completedQuestCount];
      for (int i = 0; i < completedQuestCount; i++)
        quests[i] = SVTHelper.ReadString(reader);
      game.CompletedQuests = quests;
    }

    private static void ReadIncompletedQuests(SaveGame game, BinaryReader reader)
    {
      uint incompleteQuestCount = reader.ReadUInt32();
      IncompleteQuest[] incompleteQuests = new IncompleteQuest[incompleteQuestCount];
      for (int i = 0; i < incompleteQuestCount; i++)
        incompleteQuests[i] = IncompleteQuest.Read(reader);
      game.IncompleteQuests = incompleteQuests;
    }

    /// <summary>
    /// Save the game out the file system
    /// </summary>
    /// <param name="filename">File to save the game to</param>
    public void Save(string filename)
    {
      if (filename == null)
        throw new ArgumentNullException("filename");

      BinaryWriter output = null;
      try
      {
        CreateFileBackup(filename);
        output = new BinaryWriter(new FileStream(filename, FileMode.OpenOrCreate, FileAccess.ReadWrite));
        // TODO: Write the game back out to the file system
      }
      finally
      {
        if (output != null)
          output.Close();
      }
    }

    /// <summary>
    /// Create a backup of the file, the backup file will have the extension "*.bak"
    /// </summary>
    /// <param name="filename">File to backup</param>
    private static void CreateFileBackup(string filename)
    {
      if (File.Exists(filename))
      {
        string destFileName = Path.ChangeExtension(filename, GAME_BACKUP_EXT);
        File.Copy(filename, destFileName, true);
      }
    }
  }
}
